package controller;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import entity.Bill;
import entity.Criteria;
import entity.LayuiEntity;
import service.BillService;
import service.impl.BillServiceImpl;
/////
@Controller
public class BillController {

	@Autowired
	private BillService service;

	/**
	 * 
	 * @param page  layui����ҳ������±����ֻᷢ�͵Ĳ���
	 * @param limit layui���͵Ĳ��� ÿҳ������Ĭ��10
	 */
	@RequestMapping("loadLayuiTable")
	@ResponseBody
	public LayuiEntity<Bill> loadLayuiTable(@RequestParam(defaultValue = "1") Integer page, Integer limit,
			String productName, // ģ����ѯ
			Integer id) // id��ѯ

	{
		// �����ҳ
		Integer offset = 5; // Ĭ��ÿҳ5��
		Integer start = (page - 1) * 5;
		// ��������
		Criteria cr = new Criteria();
		cr.setId(id);
		cr.setProductName(productName);
		cr.setStart(start);
		cr.setOffset(offset);

		// ִ�в�ѯ
		List<Bill> list = service.findBillCriteria(cr);
		// ͳ������
		Integer count = service.getCount();
		// ��װlayui��Ҫ�����ݽ��з���
		// {"code":0,"msg":"","count":1000,"data":[{"id":10000,"usernam...
		LayuiEntity<Bill> layui = new LayuiEntity<Bill>();
		layui.setCount(count);
		layui.setData(list);
		return layui;
	}

	// �޸ı��ύ��url
	@RequestMapping("updateBill")
	@ResponseBody
	public String updateBill(Bill bill) {
		try {
			service.updateBill(bill);
			return "success";
		} catch (Exception e) {
			return "fail";
		}
	}

	// ��Ӷ��������ݿ�
	@RequestMapping("addBill")
	@ResponseBody
	public String addBill(Bill bill) {
		try {
			service.addBill(bill);
			return "success";
		} catch (Exception e) {
			return "fail";
		}
	}

	// 根据id删除表格的行
	@RequestMapping("deleteBillRow")
	@ResponseBody
	public String deleteBillRow(Integer id) {
		// 进行权限判断，只有管理员才能删除
		Subject subject = SecurityUtils.getSubject();
		if (subject.hasRole("管理员")) {
			service.deleteBill(id);
			return "success";
		} else {
			//如果不是管理员角色则不进行删除，直接返回fail失败
			return "fail";
		}

	}

}
